<template>

  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption"
                       :data="treeData"
                       @node-click="nodeClick">
              <span class="el-tree-node__label"
                    slot-scope="{ node }">
                <span>
                  <i class="el-icon-user-solid"></i>
                  {{ (node || {}).label }}
                </span>
              </span>
            </avue-tree>
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud v-bind="bindVal"
                   v-on="onEvent"
                   :page.sync="page"
                   v-model="form"
                   :before-open="beforeOpen"
                   v-permission="{addBtn: 'SYSTEM_USER_ADD',editBtn: 'SYSTEM_USER_UPDATE',delBtn: 'SYSTEM_USER_DELETE',viewBtn: 'USER_DETAIL'}"
                   :permission="this.customizePermission"
                   ref="crud"
                   :before-close="beforeClose">
          <template slot="menuLeft" slot-scope="{size}">
            <el-button type="danger"
                       v-permission="'SYSTEM_USER_DELETE'"
                       icon="el-icon-delete"
                       :size="size"
                       @click.stop="deletes()">批量删除
            </el-button>

            <el-button :size="size"
                       plain
                       icon="el-icon-s-custom"
                       v-permission="'SYSTEM_USER_UPDATEROLE'"
                       @click="handleGrant">角色配置
            </el-button>
            <el-button :size="size"
                       plain
                       icon="el-icon-refresh"
                       v-permission="'SYSTEM_USER_RESETPASSWORD'"
                       @click="handleReset">密码重置
            </el-button>

            <el-button  :size="size"
                       type="success"
                       plain
                       icon="el-icon-download"
                       v-permission="'SYSTEM_USER_IMPORTUSER'"
                       @click.stop="handleUpload">导入</el-button>

            <el-button type="warning"
                       :size="size"
                       plain
                       v-permission="'SYSTEM_USER_EXPORTUSER'"
                       icon="el-icon-upload2"
                       @click="handleExport">导出
            </el-button>

          </template>

          <template slot="onLine" slot-scope="scope">

            <el-badge v-if="scope.row.onLine > 0" :value="scope.row.onLine" :max="10" style="margin-top: 10px;" type="success">
              <span @click="showOnline(scope.row.id)" style="color: #07c160;cursor: pointer">在线</span>
            </el-badge>
            <span v-else style="color: #ABABAB">离线</span>


          </template>

          <template slot="userType" slot-scope="scope">
            <el-tag>{{scope.row.userTypeStr}}</el-tag>
          </template>

          <template slot="activationStatus" slot-scope="scope">
            <el-tag>{{scope.row.activationStatusStr}}</el-tag>
          </template>

        </avue-crud>
      </basic-container>
    </el-col>
    <el-dialog title="用户角色配置"
               custom-class="avue-dialog" class="avue-dialog"
               v-dialogDrag
               :close-on-click-modal="false"
               append-to-body
               :visible.sync="roleBox"
               width="345px">
      <el-tree :data="roleGrantList"
               show-checkbox
               check-strictly
               default-expand-all
               check-on-click-node
               :expand-on-click-node="false"
               node-key="id"
               ref="treeRole"
               :default-checked-keys="roleTreeObj"
               :props="roleProps">
      </el-tree>

      <span slot="footer"
            class="avue-dialog__footer">
        <el-button @click="roleBox = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitRole">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="导入用户数据"
               custom-class="avue-dialog" class="avue-dialog"
               v-dialogDrag
               :close-on-click-modal="false"
               append-to-body
               :visible.sync="isUpload"
               width="555px">
      <avue-form :option="excelOption" ref="updateFrom" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" size="small" icon="el-icon-download" @click="handleTemplate">
            点击下载
          </el-button>
        </template>
      </avue-form>
    </el-dialog>

    <el-dialog v-permission="'USER_ONLINE'"
               title="在线信息"
               custom-class="avue-dialog" class="avue-dialog"
               v-dialogDrag
               :close-on-click-modal="false"
               append-to-body
               :visible.sync="isOnLine"
               width="755px">

      <el-table :data="onLineList" style="width: 100%" >

        <el-table-column fixed label="客户端" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.client }}</span>
          </template>
        </el-table-column>

        <el-table-column label="登录IP" align="center">
          <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.ip }}</span>
          </template>
        </el-table-column>

        <el-table-column label="登录时间" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.date }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button v-permission="'USER_OFFLINE'" size="mini" :type="scope.row.flag?'info':'success'" @click="scope.row.flag?'':offline(scope.row)">{{scope.row.flag?'已下线':'下线'}}</el-button>
          </template>
        </el-table-column>

      </el-table>

    </el-dialog>

  </el-row>
</template>

<script>
import {
  getRoleList,
  resetPassword,
  addRoles,
  getOrgTree,
  getPost,
  exportUser,
  downloadTemplate
} from '@/api/system/user'
import { jsonToParams } from '@/util/util'
import { validatenull } from '@/util/validate'
import {mapGetters} from "vuex";
export default window.$crudCommon({
  data () {
    return {
      edit: false,
      del: false,
      isResetPassword: false,
      isImportUser: false,
      excel: false,
      isAddRole: false,
      roleProps: {
        label: "name",
        value: "id"
      },
      roleTreeObj: {},
      roleGrantList: [],
      roleBox: false,
      isUpload: false,
      count: 0,
      excelBox: false,
      treeData: [],
      treeOption: {
        nodeKey: 'key',
        addBtn: false,
        menu: false,
        props: {
          label: 'name',
          value: 'id'
        }
      },
      excelForm: {
        isCover: 0
      },
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '上传文件',
            prop: 'file',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            accept: '.xls,.xlsx',
            propsHttp: {
              res: 'data'
            },
            data: {"isCover": 0},
            tip: '请上传 .xls,.xlsx 模板格式文件',
            action: window.urllist.user+"/core/user/importUser"
          },
          {
            label: "覆盖数据",
            prop: "isCover",
            type: "switch",
            dicUrl: window.urllist.dictUrl + 'YN01',
            props: {
              label: "name",
              value: "code"
            },
            hide: true,
            row:true,
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      },
      isStart: true,
      selectOrgId:  '',
      isOnLine:  false,
      onLineList: []
    }
  },
  created () {
    getOrgTree().then(res => {
      this.treeData = res.data.data;
    });
  },
  filters: {
  },
  watch: {
    'form.tenantCode'(tenantCode) {
      if (!validatenull(tenantCode)) {
        if (!this.isStart){
          this.form.orgId="";
          this.form.postId="";
        }else {
          this.isStart = false;
        }

        getOrgTree({"tenantCode": tenantCode}).then(res => {
          this.findObject(this.$refs.crud.option.group[0].column, "orgId").dicData = res.data.data;
        });

        getPost({"tenantCode": tenantCode}).then(res => {
          this.findObject(this.$refs.crud.option.group[0].column, "postId").dicData = res.data.data;
        });
      }else {
        this.form.orgId="";
        this.form.postId="";
        this.findObject(this.$refs.crud.option.group[0].column, "orgId").dicData = [];
        this.findObject(this.$refs.crud.option.group[0].column, "postId").dicData = [];
      }
    },
    'excelForm.isCover' () {
      this.findObject(this.excelOption.column, 'file').data = {"isCover" : this.excelForm.isCover};
    }
  },
  computed: {
    ...mapGetters(["website"]),
  },
  methods: {
    showOnline (id) {

        this.api['online'](id).then(res=>{
          this.onLineList = res.data.data.map(v=>{
            return {...v,flag:false}
          })
          this.isOnLine = true;
        });


    },
    offline(data){

      this.api['offline']({userId:data.userId,token:data.token}).then(res=>{
        if (res.data.status){
          data.flag = true;

          this.$refs.crud.data.forEach(dt=>{
            if (dt.id === data.userId){
              dt.onLine--;
            }
          })
        }
      });
    },
    customizePermission (key,row) {
      if (key === 'delBtn') {
        if (row){
          //超级用户和匿名用户不可删除
          if (row.id === this.website.rootRoleId || row.id === this.website.anonymousRoleId){
            return false;
          }
        }
      }
      return true;
    },
    beforeClose(done){
      this.isStart = true;
      done();
    },
    submitRole () {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
      addRoles({
        userIds: this.ids,
        roleIds: roleList
      }).then(() => {
        this.roleBox = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.getList();
      });
    },
    handleUpload () {
      this.excelForm = {
        isCover: 0
      }
      this.isUpload = true
    },
    handleTemplate() {
      downloadTemplate();
    },
    uploadAfter(res, done) {
      done();
      this.isUpload = false;
      this.refreshChange();
    },
    handleGrant () {
      if (this.selection.length <= 0) {
        this.$message.warning("请至少选择一条数据");
        return;
      }
      this.roleTreeObj = [];
      if (this.selection.length === 1) {
        this.roleTreeObj = (this.selection[0].roleIds || '').split(",");
      }


      let tenantCode = this.selection[0].tenantCode;
      let is = true;
      Object.keys(this.selection).forEach(ele => {
        if (tenantCode !== this.selection[ele].tenantCode){
          is = false;
        }
      });
      if (is){
        let param = {};
        if (this.$store.getters.isShowTenantCode){
          param = {"tenantCode": tenantCode};
        }
        getRoleList(param).then(res => {
          this.roleGrantList = res.data.data;
          this.roleBox = true;
        });
      }else {
        this.$message.warning("只能选择同一租户的用户设置角色");
      }
    },
    handleExport(){

      this.$confirm("是否导出当前查询用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        exportUser(jsonToParams(this.$refs.crud.$refs.headerSearch.searchForm));
      });
    },
    handleReset () {
      if (this.selection.length === 0) {
        this.$message.warning("请至少选择一条数据");
        return;
      }
      this.$confirm("确定将选择账号密码重置?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return resetPassword(this.ids);
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    nodeClick (data) {
      this.selectOrgId = data.id;
      this.params.orgId = data.id;
      this.page.currentPage = 1;
      this.getList();
    },
    searchBefore(){
      if (!this.validatenull(this.selectOrgId)) {
        this.params.orgId = this.selectOrgId;
      }
    },
    searchResetAfter(){
      this.selectOrgId = '';
    },
    beforeOpen(done,type){
      if (["add"].includes(type)) {
        this.findObject(this.$refs.crud.option.group[0].column, 'tenantCode').value=this.$store.getters.tenantCode;
      }
      done();
    }
  }
}, {
  name: '/system/user',
  data: 'list'
})
</script>

<style lang="scss" scoped>
</style>